//
//  UIScrollView+LimitedEdgesScrollable.m
//  MusicTailor
//
//  Created by dl on 2018/11/17.
//  Copyright © 2018 com.li.ding. All rights reserved.
//

#import "UIScrollView+LimitedEdgesScrollable.h"
#import <JRSwizzle/JRSwizzle.h>
#import <BlocksKit/BlocksKit.h>

static void *HBLimitedEdgesScrollableEnableKey = &HBLimitedEdgesScrollableEnableKey;
static void *HBLimitedScrollableContentRectKey = &HBLimitedScrollableContentRectKey;

@implementation UIScrollView (LimitedEdgesScrollable)

+ (void) load {
    [UIScrollView.class jr_swizzleMethod:@selector(gestureRecognizerShouldBegin:) withMethod:@selector(hb_gestureRecognizerShouldBegin:) error:nil];
}

- (BOOL) hb_gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if ([self hb_limitedEdgesScrollableEnable]
        && [gestureRecognizer isKindOfClass:[UIPanGestureRecognizer class]]) {
        CGPoint translation = [(UIPanGestureRecognizer *)gestureRecognizer translationInView:self];
        
        // 如果设置了可滑动范围，则不在范围内的不响应滑动事件
        if (!CGRectEqualToRect(self.hb_limitedScrollableContentRect, CGRectZero)) {
            CGPoint point = [gestureRecognizer locationInView:self];
            if (!CGRectContainsPoint(self.hb_limitedScrollableContentRect, point)) {
                return NO;
            }
        }
        
        // 左右
        if (fabs(translation.x) > fabs(translation.y)) {
            // 右
            if (translation.x < 0) {
                return !(self.contentOffset.x + self.bounds.size.width >= self.contentSize.width);
            }
            // 左
            else {
                return !(self.contentOffset.x <= 0);
            }
        }
    }
    return [self hb_gestureRecognizerShouldBegin:gestureRecognizer];
}

- (void) hb_setLimitedEdgesScrollableEnable:(BOOL)hb_limitedEdgesScrollableEnable {
    [self bk_associateValue:@(hb_limitedEdgesScrollableEnable) withKey:HBLimitedEdgesScrollableEnableKey];
}

- (BOOL) hb_limitedEdgesScrollableEnable {
    return [[self bk_associatedValueForKey:HBLimitedEdgesScrollableEnableKey] boolValue];
}

@end

@implementation UIScrollView (LimitedContentRectScrollable)

- (void) hb_setLimitedScrollableContentRect:(CGRect)hb_limitedScrollableContentRect {
    [self bk_associateValue:[NSValue valueWithCGRect:hb_limitedScrollableContentRect] withKey:HBLimitedScrollableContentRectKey];
}

- (CGRect) hb_limitedScrollableContentRect {
    return [[self bk_associatedValueForKey:HBLimitedScrollableContentRectKey] CGRectValue];
}

@end
